import sys
from PySide6.QtWidgets import (
    QMainWindow, QApplication, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton, QTabWidget, QStatusBar,
    QFileDialog, QMenuBar, QMenu, QToolBar, QMessageBox
)
from PySide6.QtGui import QIcon, QAction
from PySide6.QtCore import Qt, QSize
from core.data_loader import DataLoader
from ui.data_view import DataTableView
from ui.analysis_panel import AnalysisPanel
from ui.resources import Resources

class MainWindow(QMainWindow):
    """MiniBox Pro主窗口"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("MiniBox Pro")
        self.setGeometry(100, 100, 1200, 800)
        
        # 初始化资源
        self.res = Resources()
        
        # 初始化数据加载器
        self.loader = DataLoader()
        self.current_data = None
        
        # 设置UI
        self._setup_ui()
        self._setup_menu()
        self._setup_toolbar()
        self._setup_statusbar()
        
        # 应用样式
        self._apply_styles()
    
    def _setup_ui(self):
        """设置主界面布局"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout()
        central_widget.setLayout(main_layout)
        
        # 顶部控制栏
        control_layout = QHBoxLayout()
        self.source_input = QLineEdit()
        self.source_input.setPlaceholderText("输入文件路径或API URL...")
        self.browse_btn = QPushButton("浏览")
        self.browse_btn.setIcon(self.res.icon('folder'))
        self.load_btn = QPushButton("加载")
        self.load_btn.setIcon(self.res.icon('import'))
        
        control_layout.addWidget(QLabel("数据源:"))
        control_layout.addWidget(self.source_input, 1)
        control_layout.addWidget(self.browse_btn)
        control_layout.addWidget(self.load_btn)
        main_layout.addLayout(control_layout)
        
        # 主内容区
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget, 1)
        
        # 数据视图标签
        self.data_tab = QWidget()
        self.data_tab_layout = QVBoxLayout()
        self.data_tab.setLayout(self.data_tab_layout)
        
        self.data_view = DataTableView()
        self.data_tab_layout.addWidget(self.data_view)
        
        self.tab_widget.addTab(self.data_tab, self.res.icon('table'), "数据视图")
        
        # 分析标签
        self.analysis_tab = AnalysisPanel()
        self.tab_widget.addTab(self.analysis_tab, self.res.icon('chart'), "分析")
        
        # 连接信号
        self.browse_btn.clicked.connect(self._browse_file)
        self.load_btn.clicked.connect(self._load_data)
    
    def _setup_menu(self):
        """设置菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件")
        
        open_action = QAction(self.res.icon('import'), "打开", self)
        open_action.triggered.connect(self._browse_file)
        file_menu.addAction(open_action)
        
        export_menu = file_menu.addMenu(self.res.icon('export'), "导出")
        
        export_csv = QAction("CSV", self)
        export_csv.triggered.connect(lambda: self._export_data('csv'))
        export_menu.addAction(export_csv)
        
        export_excel = QAction("Excel", self)
        export_excel.triggered.connect(lambda: self._export_data('excel'))
        export_menu.addAction(export_excel)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 分析菜单
        analysis_menu = menubar.addMenu("分析")
        
        stats_action = QAction(self.res.icon('stats'), "描述统计", self)
        stats_action.triggered.connect(self._show_stats)
        analysis_menu.addAction(stats_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助")
        
        about_action = QAction("关于", self)
        about_action.triggered.connect(self._show_about)
        help_menu.addAction(about_action)
    
    def _setup_toolbar(self):
        """设置工具栏"""
        toolbar = QToolBar("主工具栏")
        toolbar.setIconSize(QSize(24, 24))
        self.addToolBar(toolbar)
        
        # 添加工具按钮
        open_btn = QAction(self.res.icon('import'), "打开", self)
        open_btn.triggered.connect(self._browse_file)
        toolbar.addAction(open_btn)
        
        refresh_btn = QAction(self.res.icon('refresh'), "刷新", self)
        refresh_btn.triggered.connect(self._refresh_data)
        toolbar.addAction(refresh_btn)
        
        toolbar.addSeparator()
        
        stats_btn = QAction(self.res.icon('stats'), "统计", self)
        stats_btn.triggered.connect(self._show_stats)
        toolbar.addAction(stats_btn)
        
        chart_btn = QAction(self.res.icon('chart'), "图表", self)
        chart_btn.triggered.connect(self._show_chart)
        toolbar.addAction(chart_btn)
    
    def _setup_statusbar(self):
        """设置状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        
        self.status_label = QLabel("就绪")
        self.status_bar.addWidget(self.status_label, 1)
    
    def _apply_styles(self):
        """应用样式表"""
        self.setStyleSheet("""
            QMainWindow {
                background-color: #ffffff;
            }
            QTabWidget::pane {
                border: 1px solid #dddddd;
                background: white;
            }
            QTabBar::tab {
                background: #f0f0f0;
                color: #333333;
                padding: 8px;
                border: 1px solid #dddddd;
                border-bottom: none;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
            }
            QTabBar::tab:selected {
                background: white;
                color: #0066cc;
                border-bottom: 2px solid #0066cc;
            }
            QTableView {
                border: 1px solid #dddddd;
                gridline-color: #eeeeee;
                alternate-background-color: #f9f9f9;
            }
            QHeaderView::section {
                background-color: #f0f0f0;
                padding: 5px;
                border: 1px solid #dddddd;
            }
            QPushButton {
                padding: 5px 10px;
                background-color: #f0f0f0;
                border: 1px solid #cccccc;
                border-radius: 4px;
                min-width: 70px;
            }
            QPushButton:hover {
                background-color: #e0e0e0;
            }
            QPushButton:pressed {
                background-color: #d0d0d0;
            }
            QLineEdit {
                padding: 5px;
                border: 1px solid #cccccc;
                border-radius: 4px;
            }
        """)
    
    def _browse_file(self):
        """浏览文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择数据文件", "", 
            "数据文件 (*.xlsx *.csv *.json);;所有文件 (*)"
        )
        if file_path:
            self.source_input.setText(file_path)
    
    def _load_data(self):
        """加载数据"""
        source = self.source_input.text().strip()
        if not source:
            QMessageBox.warning(self, "警告", "请输入数据源路径")
            return
        
        try:
            self.status_label.setText("正在加载数据...")
            QApplication.processEvents()  # 更新UI
            
            # 加载数据
            self.current_data = self.loader.load(source)
            
            # 更新数据视图
            self.data_view.set_data(self.current_data)
            
            # 更新分析面板
            self.analysis_tab.set_data(self.current_data)
            
            self.status_label.setText(f"数据加载成功 - {len(self.current_data)}行×{len(self.current_data.columns)}列")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载数据失败: {str(e)}")
            self.status_label.setText("数据加载失败")
    
    def _refresh_data(self):
        """刷新数据"""
        if self.source_input.text():
            self._load_data()
    
    def _export_data(self, format_type):
        """导出数据"""
        if self.current_data is None:
            QMessageBox.warning(self, "警告", "没有可导出的数据")
            return
        
        file_path, _ = QFileDialog.getSaveFileName(
            self, f"导出为{format_type.upper()}", "", 
            f"{format_type.upper()}文件 (*.{format_type})"
        )
        if not file_path:
            return
        
        try:
            if format_type == 'csv':
                self.current_data.to_csv(file_path, index=False)
            elif format_type == 'excel':
                self.current_data.to_excel(file_path, index=False)
            
            QMessageBox.information(self, "成功", "数据导出成功")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出失败: {str(e)}")
    
    def _show_stats(self):
        """显示统计信息"""
        if self.current_data is None:
            QMessageBox.warning(self, "警告", "没有可分析的数据")
            return
        
        self.tab_widget.setCurrentIndex(1)
        self.analysis_tab.show_stats()
    
    def _show_chart(self):
        """显示图表"""
        if self.current_data is None:
            QMessageBox.warning(self, "警告", "没有可分析的数据")
            return
        
        self.tab_widget.setCurrentIndex(1)
        self.analysis_tab.show_chart()
    
    def _show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于 MiniBox Pro", 
                         "<h2>MiniBox Pro</h2>"
                         "<p>版本 1.0.0</p>"
                         "<p>多功能数据分析工具</p>"
                         "<p>© 2025 MiniBox Team</p>")

def run_app():
    """运行应用程序"""
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

if __name__ == '__main__':
    run_app()